<template>
	<view :class="{disabled:!btnEnable}" @click="sendcode" class="code-button" >
		{{btnText}}
	</view>
</template>
<script>
	export default {
		name: 'CodeButton',
		data() {
			return {
				btnEnable: true,
				btnText: '获取验证码'
			}
		},
		onLoad(e) {

		},
		props: {
			action: {
				type: String,
				default: 'login'
			},
			phone: {
				type: String,
				default: null
			},
		},
		methods: {
			sendcode() {
				
				if (!this.btnEnable) {
					return true
				}
				
				if (this.phone.length == 0) {
					this.$emit('setError', '手机号码不能为空')
				} else if (!this.phone.match(/^(?:0?1)[123456789]\d{9}$/)) {
					this.$emit('setError', '手机号码格式错误')
				} else {
					this.$emit('setError', '')
					//发送验证码
					this.btnEnable = false

					this.$api.post('/sms/send',
						{
							phone: this.phone
						}
					).then((response) => {
						if (response.code != 0) {
							this.$emit('setError', response.msg)
						}
					})

					var time = 60
					this.btnText = time + '秒'
					var codeTime = setInterval(() => {
						if (time == 1) {
							clearInterval(codeTime)
							this.btnEnable = true
							this.btnText = '获取验证码'
							return true
						}
						time = time - 1
						this.btnText = time + '秒'
					}, 1000);
				}
			},
		}
	}
</script>
<style lang="scss">
	.code-button {
		font-size:$uni-font-size-base;
		padding: 20upx;
		margin-left: 30upx;
		color: black;
		background-color: #eee;
		text-align: center;
	}

</style>
